﻿''' <summary>
''' helper modul contains helper functions
''' </summary>
''' <remarks></remarks>
Module HelperModul

    ''' <summary>
    '''  kopiert alle neuen und geänderten Dateien vom sourceFolder in den destinationFolder per xcopy-Befehl.
    ''' </summary>
    ''' <param name="sourceFolder"> Quelle (Dateien, die archiviert werden sollen)</param>
    ''' <param name="destinationFolder">Ziel, Archiv in dem das backup abgelegt wird</param>
    ''' <param name="myLogfile">logfile</param>
    ''' <returns>true, wenn alles ok war</returns>
    ''' <remarks></remarks>
    Public Function makeCopy(ByVal sourceFolder As String, ByVal destinationFolder As String, ByVal myLogfile As String) As Boolean
        On Error GoTo myError
        MainModul.log.Debug("HelperModul.makeCopy() start: sourceFolder=" & sourceFolder & ", destinationFolder=" & destinationFolder)

        Dim newProc As Diagnostics.Process, myTime As Date, myTimeStr As String
        Dim returnValue As Boolean, myStater As String

        makeCopy = False
        returnValue = True

        '1.1 prüfe, ob sourceFolder existiert,wenn nicht, dann error!
        If System.IO.Directory.Exists(sourceFolder) = False Then
            Err.Raise(1001, "HelperModul.makeCopy", "Error: sourceFolder'" & sourceFolder & "' does not exists! stopping copying process!")
        End If

        '1.2 prüfe, ob die destinationFolder existiert, wenn nicht, dann erzeuge ihn:
        If System.IO.Directory.Exists(destinationFolder) = False Then
            MainModul.log.Debug("HelperModul.makeCopy() create destination folder!")
            System.IO.Directory.CreateDirectory(destinationFolder)
        End If

        'Problem: kopiert immer wieder alles, obwohl sich nix geändert hat!
        'dirs = usbDriveDirInfo.GetDirectories
        'For Each oneDir In dirs
        'sourceDirectoryName As String, 	destinationDirectoryName As String, 	overwrite As Boolean 
        'sourceDirectoryName = oneDir.FullName
        'Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(sourceDirectoryName, destinationDirectoryName, True)
        'Next oneDir
        'Lösung: call xcopy:                 Shell("cmd /c xcopy /y c:\temp\*.* C:\Temp\Backup")
        '@rem /e :: Kopiert alle Unterverzeichnisse (leer oder nicht leer).
        '@rem /c :: Setzt das Kopieren fort, auch wenn Fehler auftreten.
        '@rem /r :: Überschreibt schreibgeschützte Dateien.
        '@rem /y :: Unterdrückt die Aufforderung zur Bestätigung, dass eine vorhandene Zieldatei überschrieben werden soll.
        '@rem /d :: Kopiert nur die an oder nach dem Datum geänderten Dateien.
        '@rem            Ist kein Datum angegeben, werden nur Dateien kopiert,
        '@rem            die neuer als die bestehenden Zieldateien sind.
        '@rem /v :: Überprüft jede neue Datei auf Korrektheit
        'XCOPY %source% %target% /e /c /r /y /d /v>>%logfile%	
        myStater = "newProc"
        myTime = Now
        myTimeStr = myTime.Day & "." & myTime.Month & "." & myTime.Year & "_" & myTime.Hour & ":" & myTime.Minute & ":" & myTime.Second
        Dim shProcessID As Integer = Shell("cmd /c echo --- starting xcopy on " & myTimeStr & " using backupfolder:" & destinationFolder & " ------- >>" & myLogfile, AppWinStyle.NormalFocus, True)
        newProc = Diagnostics.Process.GetProcessById(shProcessID)
        myStater = "shProcessID=" & shProcessID

        System.Threading.Thread.Sleep(1000)

        If My.Settings.SettingLastBackup.Length > 0 Then
            myStater = "SettingLastBackup.Length > 0"
            shProcessID = Shell("cmd /c echo last backup-run:" & My.Settings.SettingLastBackup & ">>" & myLogfile, AppWinStyle.NormalFocus, True)
            System.Threading.Thread.Sleep(1000)
            myStater = "SettingLastBackup.shProcessID=" & shProcessID
        End If

        myStater = "xcopy"
        shProcessID = Shell("cmd /c xcopy " & sourceFolder & "\*.* " & destinationFolder & " /e /c /r /y /d /v >>" & myLogfile, AppWinStyle.NormalFocus, True)
        myStater = "xcopy shProcessID=" & shProcessID

        System.Threading.Thread.Sleep(2000)
        myTime = Now
        myTimeStr = myTime.Day & "." & myTime.Month & "." & myTime.Year & "_" & myTime.Hour & ":" & myTime.Minute & ":" & myTime.Second
        myStater = "ending xcopy time=" & myTimeStr
        shProcessID = Shell("cmd /c echo --- ending xcopy on " & myTimeStr & " ------- >>" & myLogfile, AppWinStyle.NormalFocus, True)

myExit:
        MainModul.log.Debug("HelperModul.makeCopy() exit: returnValue=" & returnValue)
        makeCopy = returnValue
        Exit Function
myError:
        Dim errMsg As String
        errMsg = "HelperModul.makeCopy() Stater:" & myStater & "-Error:" & Err.Number & ":" & Err.Description
        MainModul.log.Error(errMsg)
        MsgBox(errMsg, MsgBoxStyle.Critical, "")
        returnValue = False
        Resume myExit

    End Function

    ''' <summary>
    ''' searches for the driveName and if found then returns a collection of:
    ''' first element: key:finder ==true or false
    ''' second element: key: DriveInfo Itemtyp:System.IO.DriveInfo
    ''' 
    ''' searching for DriveTypes:
    ''' - IO.DriveType.Removable (The drive is a removable storage device, such as a floppy disk drive or a USB flash drive.)
    ''' - IO.DriveType.Fixed (The drive is a fixed disk.)
    ''' - IO.DriveType.Network (The drive is a network drive.)
    ''' </summary>
    ''' <param name="driveName">drive Name</param>
    ''' <returns>collection</returns>
    ''' <remarks></remarks>
    Public Function finderBackupDrive(ByVal driveName As String) As Collection
        MainModul.log.Debug("finderBackupDrive() start: searching for driveName=" & driveName)

        Dim myDriveInfo As System.IO.DriveInfo = Nothing
        Dim finder As Boolean = False
        Dim myCol As New Collection

        Dim driveInfos = System.IO.DriveInfo.GetDrives()
        For Each oneDriveInfo In driveInfos

            MainModul.log.Debug("HelperModul.finderBackupDrive() RootDirectoryName=" & oneDriveInfo.RootDirectory.Name)
            MainModul.log.Debug("HelperModul.finderBackupDrive() Drivetype:" & oneDriveInfo.DriveType & ", VolumeLabel:" & oneDriveInfo.VolumeLabel)

            If oneDriveInfo.DriveType = IO.DriveType.Removable Or oneDriveInfo.DriveType = IO.DriveType.Fixed Or oneDriveInfo.DriveType = IO.DriveType.Network Then
                If oneDriveInfo.VolumeLabel.ToLower = driveName.ToLower Then
                    'found Backup-Drive!
                    MainModul.log.Info("HelperModul.finderBackupDrive() found drive, RootDirectory.FullName=" & oneDriveInfo.RootDirectory.FullName)
                    finder = True
                    myDriveInfo = oneDriveInfo
                    Exit For
                End If
            End If

        Next

        myCol.Add(Key:="finder", Item:=finder)
        myCol.Add(Key:="DriveInfo", Item:=myDriveInfo)
        MainModul.log.Debug("HelperModul.finderBackupDrive() exit: is drivename found?=" & finder)
        Return myCol
    End Function


    ''' <summary>
    ''' check arguments:
    ''' 1. no args found (cmdArgs.Length=0): returns false
    ''' 2. if is the length of arguments less then needed arguments, then returns false
    ''' </summary>
    ''' <param name="cmdArgs">array of arguments by the caller</param>
    ''' <param name="neededArgs">Anzahl der benötigten Argumente</param>
    ''' <returns>true or false</returns>
    ''' <remarks></remarks>
    Public Function checkArgs(ByVal cmdArgs() As String, ByVal neededArgs As Integer) As Boolean
        MainModul.log.Debug("HelperModul.checkArgs() start: cmdArgsLength=" & cmdArgs.Length)
        Dim returnValue As Boolean, i As Integer
        returnValue = True
        If cmdArgs.Length = 0 Then
            'no args found! returns false
            returnValue = False
        Else
            'logge alle args:
            For i = 1 To cmdArgs.Length
                MainModul.log.Debug("HelperModul.checkArgs() found arg(" & i & ") =" & cmdArgs(i - 1))
            Next i

            If cmdArgs.Length < neededArgs Then
                returnValue = False
            End If
        End If
        MainModul.log.Debug("HelperModul.checkArgs() end: returnValue=" & returnValue)
        Return returnValue
    End Function


    ''' <summary>
    ''' getAssemblyInfos returns from the assemblyInfo.vb:
    '''  - Title
    '''  - FileVersion
    ''' on error an empty String.
    ''' </summary>
    Public Function getAssemblyInfos() As String
        On Error GoTo myErr
        MainModul.log.Debug("HelperModul.getAssemblyInfos() starting")
        Dim returnValue As String = ""

        Dim customAttributes As Object() = System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(False)
        Dim oneObj As Object
        For Each oneObj In customAttributes
            log.Debug("HelperModul.getAssemblyInfos:" & oneObj.GetType.FullName())
            If TypeOf oneObj Is System.Reflection.AssemblyTitleAttribute Then
                Dim myAssembyTitle As System.Reflection.AssemblyTitleAttribute = oneObj
                returnValue = returnValue & "" & myAssembyTitle.Title & " "
            End If

            If TypeOf oneObj Is System.Reflection.AssemblyFileVersionAttribute Then
                Dim myAssembyFileVersion As System.Reflection.AssemblyFileVersionAttribute = oneObj
                returnValue = returnValue & "V " & myAssembyFileVersion.Version & " "
            End If

        Next oneObj
myExit:
        MainModul.log.Debug("HelperModul.getAssemblyInfos() end: returnValue=" & returnValue)
        getAssemblyInfos = returnValue
        Exit Function
myErr:
        returnValue = ""
        Dim errMsg As String
        errMsg = Err.Number & ":" & Err.Description
        MsgBox(errMsg, MsgBoxStyle.Critical, "HelperModul.getAssemblyInfos() meldet:")
        MainModul.log.Error("HelperModul.getAssemblyInfos() error:" & errMsg)
        Resume myExit
    End Function
End Module
